package com.mc.web;

import org.apache.log4j.Logger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.mc.model.DdType;
import com.mc.model.Path;
import com.mc.model.data_download;
import com.mc.service.IDataService;
import com.mc.service.IDdtypeService;
import com.mc.utils.FileUtil;
import com.mc.utils.PathUtil;
import com.mc.utils.StringUtil2;
import com.mc.utils.TraderCenterUtil;
import com.mc.utils.XMLParserUtil;

@Controller
@RequestMapping("/backend")
public class FileAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(FileAction.class);

	private Path path = null;
	public String TITLE = "";
	@Autowired private IDataService dataService;
	@Autowired private IDdtypeService ddtypeService;
	/**
	 * 
	 * @param modelMap
	 * @return 上传文件的界面
	 */
	@RequestMapping("/uploadui")
	public String uploadui(ModelMap modelMap)
	{
		List<DdType> ddTypes = ddtypeService.allddtype();
		modelMap.addAttribute("ddTypes", ddTypes);
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:uploadFile","ViewTitle:上传文件","smenu:file","mmenu:upload"});				
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param files 需要上传的文件
	 * @param modelMap 
	 * @param dataName 文件的名称
	 * @param ddtype 文件的类型
	 * @return 管理文件的界面
	 */
	@RequestMapping("/uploadfile")
	public String uploadFile(@RequestParam(value = "files", 
	 required = false) MultipartFile [] files,ModelMap modelMap,
	 @RequestParam("dataName")String dataName,@RequestParam("ddtype")int ddtype)
	 {
		 String filepath = FileUtil.getInstance().uploadFiels(files);
		 //logger.info(filepath);
		 data_download record = new data_download();
		 record.setDataName(dataName);
		 record.setDataPath(filepath);
		 DdType ddtyId = ddtypeService.selectByPrimaryKey(ddtype);
		record.setDdtyId(ddtyId );
		 int reflect_row = dataService.insert(record );
		 if(reflect_row==1)
			{
			modelMap.addAttribute("success", true);
			}else if(reflect_row==0){
				modelMap.addAttribute("success", false);
			}
		 modelMap.addAttribute("message",true);
		 return "forward:/backend/ZiliaoManeger/1";
	 }
	/**
	 * 
	 * @param num 当前管理文件的当前页大小
	 * @param modelMap
	 * @return 管理文件的界面
	 */
	@RequestMapping("/ZiliaoManeger/{pageNum}")
	 public String ZiliaoManeger(@PathVariable("pageNum") int num,ModelMap modelMap){
		 int perPage = 8;// 每页显示新闻条数
			//ModelAndView mav = new ModelAndView();
			int rowCount = dataService.selectAllCount();
			int pagecount = rowCount % perPage;
			if (pagecount == 0)// 偶数条记录
				modelMap.addAttribute("pageCount", rowCount / perPage);
			else
				// 奇数条记录
				modelMap.addAttribute("pageCount", rowCount / perPage + 1);
			List<data_download> nab = dataService.selectAllLimit((num-1)*perPage, perPage);
			modelMap.addAttribute("pageNow", num);
			modelMap.addAttribute("allnews", nab);
			modelMap.addAttribute("searchResult", false);
			path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:downloadData","ViewTitle:文件管理","smenu:file","mmenu:filemag"});
			return PathUtil.returnStr(path, modelMap);
			//	return mav;
	 }
	/**
	 * 
	 * @param num 当前管理文件的当前页大小
	 * @param modelMap
	 * @return 管理文件的界面
	 */
	@RequestMapping("/searchdata/{pageNum}")
	 public String ZiliaoManegers(@PathVariable("pageNum") int num,ModelMap modelMap,
			 @RequestParam(value= "datatitle",required=false)String title){
		
		    int perPage = 8;// 每页显示新闻条数
		    if(title!=null){
				TITLE=title;
			}
			
			//ModelAndView mav = new ModelAndView();
			int rowCount = dataService.countofbytitlelike(TITLE);
			
			int pagecount = rowCount % perPage;
			if (pagecount == 0)// 偶数条记录
				modelMap.addAttribute("pageCount", rowCount / perPage);
			else
				// 奇数条记录
				modelMap.addAttribute("pageCount", rowCount / perPage + 1);
			List<data_download> nab = dataService.selectbytitlelike(TITLE, (num-1)*perPage, perPage);
			modelMap.addAttribute("pageNow", num);
			modelMap.addAttribute("rowCount", rowCount);
			modelMap.addAttribute("allnews", nab);
			modelMap.addAttribute("searchResult", true);
			path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:downloadData","ViewTitle:文件管理","smenu:file","mmenu:filemag"});
			return PathUtil.returnStr(path, modelMap);
			//	return mav;
	 }
	/**
	 * 
	 * @param id  需要进行ajax删除的文件的id
	 * @param modelMap
	 * @param request 用于获取跨域ajax需要返回的js函数的名称
	 * @return  ajax返回元页面，进行异步的刷新
	 */ 
	@RequestMapping("/delFile")
	@ResponseBody
	 public String delFile(@RequestParam("id") int id,ModelMap modelMap,HttpServletRequest request)
	 {
		logger.info(id);
		int resultCode = dataService.deleteByPrimaryKey(id);
		// System.out.println(resultCode);
		 String callbackFunName = request.getParameter("callbackparam");
		 if(resultCode!=0)
		 {
			// modelMap.addAttribute("delFile", true);	 
			 return callbackFunName +"("+ "{'success':true}" +")";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return callbackFunName +"("+ "{'success':false}" +")";
		 }
		
		
		

		 
		// return "forward:/backend/ZiliaoManeger/1";
	 }
	/**
	 * 
	 * @param filename 要下载的文件名臣
	 * @param response 
	 */
	@RequestMapping("/download")  
    public void downloadFile(@RequestParam("filename")String filename,HttpServletResponse response){  
        response.setCharacterEncoding("utf-8"); 
       // System.out.println(filename);
        response.setContentType("multipart/form-data"); 
        Map<String,String> filepro = XMLParserUtil.getInstance().ParserUtil("file.xml");
        String urlHeader = StringUtil2.getInstance().getPhysicsPath(filepro.get("filepath"));
        String realFileName =urlHeader+File.separator+ filename ;
        response.setHeader("Content-Disposition", "attachment;fileName="+filename);  
        try {  
            File file=new File(realFileName);  
             
            InputStream inputStream=new FileInputStream(file);  
            OutputStream os=response.getOutputStream();  
            byte[] b=new byte[1024];  
            int length;  
            while((length=inputStream.read(b))>0){  
                os.write(b,0,length);  
            }  
            inputStream.close();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }
	/**
	 * 
	 * @param modelMap
	 * @return  添加文件类型的界面
	 */
	@RequestMapping("/addfiletypeui")
	public String addfiletypeui(ModelMap modelMap){
		
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:addfiletype","ViewTitle:添加文件类型","smenu:file","mmenu:filemag"});
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param modelMap
	 * @return  管理文件额理性的界面
	 */
	@RequestMapping("/mgfiletypeui")
	public String mgfiletypeui(ModelMap modelMap){
		List<DdType> ddts = ddtypeService.allddtype();
		modelMap.addAttribute("ddts",ddts);
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:mgfiletype","ViewTitle:管理文件类型","smenu:file","mmenu:filemag"});
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param record 文件类型的对象实例
	 * @param modelMap
	 * @return 管理文件类型的界面
	 */
	@RequestMapping("/addfiletype")
	public String addfiletype(DdType record,ModelMap modelMap){
		
		int reflect_row = ddtypeService.insert(record );
		 if(reflect_row==1)
			{
			modelMap.addAttribute("success", true);
			}else if(reflect_row==0){
				modelMap.addAttribute("success", false);
			}
		 modelMap.addAttribute("message",true);
		 
		 return "forward:/backend/mgfiletypeui";
	}
	/**
	 * 
	 * @param id  需要进行ajax删除的文件类型的id
	 * @param modelMap
	 * @param request 用于获取跨域ajax需要返回的js函数的名称
	 * @return  ajax返回元页面，进行异步的刷新
	 */ 
	@RequestMapping("/delfiletype")
	@ResponseBody
	 public String delfiletype(@RequestParam("id") int id,ModelMap modelMap,
			 HttpServletRequest request)
	 {
		  logger.info(id);
		 int resultCode = ddtypeService.deleteByPrimaryKey(id);
		// System.out.println(resultCode);
		 String callbackFunName = request.getParameter("callbackparam");
		 if(resultCode!=0)
		 {
			// modelMap.addAttribute("delFile", true);	 
			 return callbackFunName +"("+ "{'success':true}" +")";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return callbackFunName +"("+ "{'success':false}" +")";
		 }
		 
		// return "forward:/backend/ZiliaoManeger/1";
	 }
	/**
	 * 
	 * @param id 需要修改文件信息文件类型的id
	 * @param modelMap
	 * @return 更新制定文件类型id的界面
	 */
	@RequestMapping("/updatefiletypeui/{id}")
	public String updatefiletypeui(@PathVariable("id")int id,ModelMap modelMap){
		DdType ddtype = ddtypeService.selectByPrimaryKey(id);
		modelMap.addAttribute("ddtype", ddtype);
		path = PathUtil.setPathParams(new String[]{"PackageName:backend","ViewName:updatefiletype","ViewTitle:添加文件类型","smenu:file","mmenu:filemag"});
		return PathUtil.returnStr(path, modelMap);
	}
	/**
	 * 
	 * @param id 文件类型id
	 * @param record 文件类型的基本属性
	 * @param modelMap
	 * @return 返回管理文件类型的界面
	 */
	@RequestMapping("/updatefiletype/{id}")
	public String updatefiletype(@PathVariable("id")int id,DdType record,ModelMap modelMap){
		record.setDdtypeId(id);
		int resultCode = ddtypeService.updateByPrimaryKey(record);
		if(resultCode!=0)
		 {
			return "forward:/backend/mgfiletypeui";
		 }else{
			 //modelMap.addAttribute("delFile", false);
			 return "fail";
		 }
		
	}
}
